import React from 'react';
import * as echarts from 'echarts';
import 'echarts/extension/dataTool';
import _ from 'lodash';
import moment from 'moment';
import { getCssVariableValue } from '@/utils/utils';

import { isDark } from '#/utils/utils';
import styles from './index.less';

const xAxisFormatter = function (params) {
  let item = params.seriesData[0];
  return (item && item.name) || '';
};

export const TYPECOLOR = {
  provincial_dayahead_clearing_price_forecast: {
    name: '日前电价预测-TJ',
    color: '#64D2FF',
    averageColor: 'rgba(100, 210, 255, 0.6)',
  },
  provincial_real_clearing_price_forecast: {
    name: '实时电价预测-TJ',
    color: '#FFA71F',
    averageColor: 'rgba(255, 167, 31, 0.6)',
  },
  unify_provincial_dayahead_clearing_price: {
    name: '统一结算日前',
    color: '#30D180',
    averageColor: 'rgba(48, 209, 128, 0.6)',
  },
  unify_provincial_real_clearing_price: {
    name: '统一结算实时',
    color: '#FFD60A',
    averageColor: 'rgba(255, 214, 10, 0.6)',
  },
  unify_provincial_dayahead_clearing_price_forecast: {
    name: '统一结算日前预测-TJ',
    color: '#BF5AF2',
    averageColor: 'rgba(191, 90, 242, 0.6)',
  },
  unify_provincial_real_clearing_price_forecast: {
    name: '统一结算实时预测-TJ',
    color: '#AC8E68',
    averageColor: 'rgba(172, 142, 104, 0.6)',
  },
  provincial_dayahead_clearing_price: {
    name: '日前电价',
    color: '#0A84FF',
    averageColor: 'rgba(10, 132, 255, 0.6)',
  },
  // '2-1': {
  //   name: '电价预测-TJ',
  //   color: '#07A872',
  //   averageColor: '#127455',
  // },
  predict_day_ahead: {
    name: '电价预测-LT',
    color: '#D29E08',
    averageColor: '#8C6E15',
  },
  // '4-1': {
  //   name: '电价预测-TJ',
  //   color: '#3CB1FB',
  //   averageColor: '#3279A7',
  // },
  // '4-2': {
  //   name: '实时电价',
  //   color: '#B382F0',
  //   averageColor: '#795DA0',
  // },
  provincial_realtime_clearing_price: {
    name: '实时出清电价',
    color: '#FF5A52',
    averageColor: 'rgba(255, 90, 82, 0.6)',
  },
};

export const historyMap = {
  dayahead_clearing_price_unadjusted: {
    name: '历史日前电价',
    color: '#5E92F6',
    borderColor: '#28313D',
  },
  dayahead_clearing_price: {
    name: '历史统一结算日前',
    color: '#0A84FF',
    borderColor: 'rgba(10, 132, 255, 0.4)',
  },
  real_clearing_price: {
    name: '历史统一结算实时',
    color: '#FF5A52',
    borderColor: 'rgba(255, 90, 82, 0.4)',
  },
  dayahead_clearing_price_forecast: {
    name: '历史统一结算日前预测',
    color: '#30D180 ',
    borderColor: 'rgba(48, 209, 128, 0.4)',
  },
  real_clearing_price_forecast: {
    name: '历史统一结算实时预测 ',
    color: '#FFD60A',
    borderColor: 'rgba(255, 214, 10, 0.4)',
  },
};

export const TYPE = {
  0: {
    name: '历史参考-最低',
  },
  1: {
    name: '历史参考-Q1',
  },
  2: {
    name: '历史参考-中位',
  },
  3: {
    name: '历史参考-Q3',
  },
  4: {
    name: '历史参考-最高',
  },
};

export const averageColor = (() => {
  const obj = {};
  Object.values(TYPECOLOR).forEach((t) => {
    obj[t.color] = t.averageColor;
  });
  return obj;
})();

// 96点循环
const timeData = () => {
  let dataTimes = [];
  let time = moment().startOf('date');
  _.forEach(new Array(96), () => {
    time.add(15, 'minutes');
    const tK = time.format('HH:mm') === '00:00' ? '24:00' : time.format('HH:mm');
    dataTimes.push(tK);
  });
  return dataTimes;
};
let dataTime = timeData();

// 保留几位小数
export const NumberFormat = (value, precision) => {
  const newNum = Math.round(value * precision) / precision;
  return newNum;
};

export const _getAveragePrice = (data) => {
  const average = [];
  const newData = []; // 过滤有综合电价的数据
  let totalPrice = 0;
  data.map((item) => {
    newData.push(item);
  });
  newData.map((item) => {
    if (item === '-' || item === null) {
      totalPrice = null;
    } else {
      totalPrice += Number(item);
    }
  });
  data.map(() => {
    if (typeof totalPrice == 'object') {
      average.push('-');
    } else {
      const result = totalPrice / newData.length;
      average.push(NumberFormat(result, 100));
    }
  });
  return average;
};

export const COLUMNS = [
  {
    dataIndex: 'titls',
    title: '',
    key: 'titls',
    width: 90,
    render(text) {
      return text;
    },
  },
  {
    dataIndex: 'median',
    title: (
      <div
        style={{
          display: 'inline-block',
          width: '100%',
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textAlign: 'right',
          textOverflow: 'ellipsis',
        }}
      >
        中位数
      </div>
    ),
    key: 'median',
    width: 80,
    render(text) {
      return <div className={styles.textNode}>{text}</div>;
    },
  },
  {
    dataIndex: 'Q1',
    title: (
      <div
        style={{
          display: 'inline-block',
          width: '100%',
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textAlign: 'right',
          textOverflow: 'ellipsis',
        }}
      >
        Q1
      </div>
    ),
    key: 'Q1',
    width: 80,
    render(text) {
      return <div className={styles.textNode}>{text}</div>;
    },
  },
  {
    dataIndex: 'Q3',
    title: (
      <div
        style={{
          display: 'inline-block',
          width: '100%',
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textAlign: 'right',
          textOverflow: 'ellipsis',
        }}
      >
        Q3
      </div>
    ),
    key: 'Q3',
    width: 80,
    render(text) {
      return <div className={styles.textNode}>{text}</div>;
    },
  },
  {
    dataIndex: 'upperLimit',
    title: (
      <div
        style={{
          display: 'inline-block',
          width: '100%',
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textAlign: 'right',
          textOverflow: 'ellipsis',
        }}
      >
        Max
      </div>
    ),
    key: 'upperLimit',
    width: 80,
    render(text) {
      return <div className={styles.textNode}>{text}</div>;
    },
  },
  {
    dataIndex: 'lowerLimit',
    title: (
      <div
        style={{
          display: 'inline-block',
          width: '100%',
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textAlign: 'right',
          textOverflow: 'ellipsis',
        }}
      >
        Min
      </div>
    ),
    key: 'lowerLimit',
    width: 80,
    render(text) {
      return <div className={styles.textNode}>{text}</div>;
    },
  },
];

export const formatCopper = function (value) {
  if (isNaN(value)) {
    return '-';
  }
  return parseFloat(value).toFixed(3);
};
// 格式化名称
export const formatName = (data, index) => {
  if (data.split('-').length && data.split('-').length > 1) {
    const dataArr = data.split('-');
    return dataArr.slice(index).join('');
  }
  return data;
};

export const columns = (list, xAxisList) => {
  const lists = JSON.parse(JSON.stringify(list));
  let xAxisData = [];
  let xData = [];
  const column = [
    {
      dataIndex: 'type',
      title: '类型',
      key: '类型',
      width: 300,
      fixed: 'left',
    },
  ];
  if (lists.length) {
    lists.map((i) => {
      xData.push(...Object.keys(i?.list));
    });
    Array.from(new Set(xData)).forEach((i) => {
      dataTime.forEach((m) => {
        if (m === '24:00') {
          const dataTime = `${i} ${m}`;
          xAxisData.push(dataTime.replace(/[-|.|:]/g, ''));
        } else {
          xAxisData.push(`${moment(`${i} ${m}`).format('YYYYMMDD HHmm')}`);
        }
      });
    });

    xAxisData.forEach((item) => {
      column.push({
        dataIndex: item,
        title: item,
        key: item,
        width: 80,
        render(text) {
          return <div className={styles.textNode}>{text}</div>;
        },
      });
    });
  } else {
    xAxisList.forEach((item) => {
      column.push({
        dataIndex: item,
        title: item,
        key: item,
        width: 80,
        render(text) {
          return <div className={styles.textNode}>{text}</div>;
        },
      });
    });
  }

  return column;
};
export const electricityPriceOption = function (
  boxList,
  list,
  forecastPriceDateBodyList,
  timeline,
  xAxisList,
  yTitle,
  ctooltip,
) {
  const lists = JSON.parse(JSON.stringify(list));
  let xAxisData = [];
  let xData = [];
  let boxDataMap = {}; // 历史电价
  let legendData = []; //底部可点击名字列表
  let newseries = []; // 所有版本内容
  let pariceSeries = []; // 范围统计

  lists.map((i) => {
    xData.push(...Object.keys(i?.list));
  });
  Array.from(new Set(xData)).forEach((i) => {
    dataTime.forEach((m) => {
      if (m === '24:00') {
        const dataTime = `${i} ${m}`;
        xAxisData.push(dataTime.replace(/[-|.|:]/g, ''));
      } else {
        xAxisData.push(`${moment(`${i} ${m}`).format('YYYYMMDD HHmm')}`);
      }
    });
    Object.keys(boxList).forEach((t) => {
      if (!boxDataMap?.[t]) {
        boxDataMap[t] = [];
      }
      boxDataMap[t].push(...boxList[t]); // 历史电价多日 按日repeat
    });
  });
  function bqDatalist(data, bq = null) {
    return 96 - data?.length > 0
      ? data.concat(Array.from({ length: 96 - data?.length }, (_) => bq))
      : data;
  }

  // tooltip初始值
  let tooltip = {
    trigger: 'axis',
    extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1)',
    backgroundColor: isDark() ? '#444444' : '#F5F8FA',
    borderWidth: 0,
    textStyle: {
      color: isDark() ? 'white' : '#888E95',
      borderWidth: 0,
      borderColor: isDark() ? '' : '#1A253C4B',
      padding: 12,
    },
  };
  tooltip.axisPointer = {
    type: 'cross',
    label: {
      backgroundColor: isDark() ? '#444444' : '#F5F8FA',
      color: isDark() ? 'white' : '#888E95',
      shadowBlur: 0,
    },
  };
  tooltip.formatter = ctooltip;
  if (forecastPriceDateBodyList.length) {
    forecastPriceDateBodyList.map((bodyList) => {
      let series = [];
      Object.keys(boxDataMap).forEach((t) => {
        const { name, color, borderColor } = historyMap[t];
        let data = echarts.dataTool.prepareBoxplotData(
          boxDataMap[t]?.length ? boxDataMap[t] : boxList[t],
        );
        series.push(
          ...[
            {
              name,
              type: 'boxplot',
              data: bqDatalist(data.boxData || [], [null, null, null, null, null]),
              color,
              itemStyle: {
                color: borderColor,
              },
            }, // 异常点
            {
              name,
              type: 'scatter',
              data: bqDatalist(data.outliers || [], [null, null]),
              symbolSize: 3,
              color,
            },
          ],
        );
      });

      let listData = bodyList.filter((item) => {
        return item;
      });
      // 处理电价预测数据
      listData.forEach((item, index) => {
        const temp = TYPECOLOR[item?.curveType];
        let name = item.name || temp.name;
        let array = [];
        let averageList = [];
        let objlegendData = {};
        objlegendData['name'] = name;
        objlegendData['itemStyle'] = {
          opacity: 1,
          borderWidth: 1,
          // borderColor: temp?.color,
          // color: '#222629',
        };
        legendData.push(objlegendData);
        var serieObj = {
          id: index,
          name: name,
          type: 'line',
        };
        const listArr = item?.list;
        [...new Set(xData)].map((i) => {
          if (!listArr?.[i]?.length) {
            const temp = bqDatalist([]);
            array.push(...temp);
            averageList.push(..._getAveragePrice(temp));
            return;
          }
          const temp = listArr[i];
          array.push(
            ...(96 - temp?.length > 0
              ? temp.concat(Array.from({ length: 96 - temp?.length }, (_) => '-'))
              : temp),
          );
          // 计算日均值
          averageList.push(..._getAveragePrice(temp));
        });
        let symbol = 'circle';
        serieObj.color = temp?.color;
        serieObj.data = bqDatalist(array);
        // serieObj.curveType = item.serieObj;
        serieObj.symbol = symbol;
        serieObj.showSymbol = false;
        // serieObj.symbolSize=[100, 1],
        // serieObj.step = 'middle';
        serieObj.smooth = true;
        (serieObj.lineStyle = {
          width: 1,
        }),
          series.push(serieObj);
        // 日均
        const dayAverage = {
          id: `日均-${index}`,
          name: name,
          type: 'line',
          data: averageList,
          color: temp?.averageColor,
          // smooth: true,
          symbol: 'none',
          showSymbol: false,
          lineStyle: {
            width: 1,
            type: 'dashed',
          },
        };
        series.push(dayAverage);
      });
      newseries.push(series);
    });
  } else {
    let series = [];
    Object.keys(boxList).forEach((t) => {
      const { name, color, borderColor } = historyMap[t];
      let data = echarts.dataTool.prepareBoxplotData(boxList[t]);

      series.push({
        name,
        type: 'boxplot',
        data: bqDatalist(data.boxData || [], [null, null, null, null, null]),
        color,
        itemStyle: {
          color: borderColor,
        },
      });
    });

    pariceSeries.push(series);
  }
  let options = {
    baseOption: {
      timeline: {
        axisType: 'category',
        orient: 'vertical',
        autoPlay: false,
        inverse: true,
        playInterval: 3000,
        left: 'right',
        right: 0,
        top: 10,
        bottom: 20,
        width: 48,
        height: null,
        symbol: 'none',
        checkpointStyle: {
          symbolSize: 10,
          borderWidth: 2,
          color: 'white',
          borderColor: getCssVariableValue('--bd-primary'),
        },
        controlStyle: {
          itemSize: 13,
          showNextBtn: false,
          showPrevBtn: false,
        },
        lineStyle: {
          show: true,
          color: getCssVariableValue('--chart-x-line'),
          width: 1,
          type: 'solid',
        },
        label: {
          color: getCssVariableValue('--chart-font-color'),
        },
        data: [],
      },
      title: [],
      tooltip: tooltip,
      grid: { left: 0, right: 78, top: 10, height: '90%', containLabel: true },
      xAxis: {
        type: 'category',
        data: xAxisData.length ? xAxisData : xAxisList,
        nameGap: 12,
        axisTick: { alignWithLabel: true },
        nameTextStyle: { color: getCssVariableValue('--chart-font-color') },
        axisLabel: { color: getCssVariableValue('--chart-font-color') },
        axisLine: { lineStyle: { color: getCssVariableValue('--chart-x-line') } },
        axisPointer: {
          label: {
            backgroundColor: getCssVariableValue('--bd-primary'),
            color: getCssVariableValue('--ant-cus-font_active'),
            shadowBlur: 0,
            formatter: xAxisFormatter,
          },
          lineStyle: {
            type: 'solid',
            color: getCssVariableValue('--chart-x-line'),
          },
        },
        splitNumber: Math.random(),
      },
      yAxis: {
        type: 'value',
        axisLine: { show: false },
        axisTick: { show: false },
        nameTextStyle: { color: getCssVariableValue('--chart-font-color') },
        axisLabel: { color: getCssVariableValue('--chart-font-color') },
        splitLine: { lineStyle: { color: getCssVariableValue('--chart-y-line') } },
        splitNumber: 4,
        axisPointer: {
          label: {
            backgroundColor: getCssVariableValue('--bd-primary'),
            color: getCssVariableValue('--ant-cus-font_active'),
            shadowBlur: 0,
          },
          lineStyle: {
            type: 'solid',
            color: getCssVariableValue('--chart-x-line'),
          },
        },
      },
      // 缩放轴
      dataZoom: [
        { type: 'inside', show: false, minSpan: 1 },
        { type: 'slider', height: 20, show: false, minSpan: 1, top: '88%' },
      ],
      // 图列组件
      legend: {
        data: [...legendData, ...Object.keys(boxList).map((t) => ({ name: historyMap[t].name }))],
        top: '96%',
        // bottom: 10,
        textStyle: {
          color: getCssVariableValue('--chart-legend-color'),
          rich: {
            update_time: {
              color: '#888E95',
            },
          },
        },
        padding: [0, 35, 0, 35],
        itemWidth: 16,
        itemHeight: 8,
        inactiveColor: '#545454',
        inactiveBorderColor: '#545454',
        inactiveBorderWidth: 'inherit',
        selected: {
          ...Object.keys(boxList).reduce((a, b) => ({ ...a, [historyMap[b].name]: false }), {}),
          历史日前电价: true,
        },
      },
      series: newseries[0] || pariceSeries[0],
    },
    options: [],
  };
  for (var n = 0; n < timeline.length; n++) {
    options.baseOption.timeline.data.push(timeline[n]);
    options.options.push({
      series: newseries[n],
    });
  }
  return {
    options,
    newseries,
    xAxisData,
  };
};

export const getPoints = () => {
  let pointArray = [
    {
      dataIndex: 'titls',
      title: '总结',
      key: 'titls',
      width: 100,
    },
  ];
  const timeArr = new Array(96);
  let time = moment().startOf('date');
  _.forEach(timeArr, (value, key) => {
    time.add(15, 'minutes');
    const timeData = `${time.format('HHmm') === '0000' ? '2400' : time.format('HHmm')}`;
    pointArray.push({
      dataIndex: key,
      title: timeData,
      key: key,
      width: 80,
      // align: 'center',
    });
  });
  return pointArray;
};

const MAPARR = [
  { title: '日前电价', key: 'daysAgo' },
  { title: '实时电价', key: 'present' },
];

export const getDetail = (param, dataSecond) => {
  const { boxData } = param;
  let data = [];
  boxData.length > 0 &&
    MAPARR.forEach((item) => {
      let obj = {
        key: item.key,
        titls: item.title,
      };
      const childrenArr = [];
      const timeArr = new Array(96);
      let time = moment().startOf('date');
      _.forEach(timeArr, (value, key) => {
        time.add(15, 'minutes');
        const timeData = `${time.format('HHmm') === '0000' ? '2400' : time.format('HHmm')}`;
        if (item.key === 'daysAgo') {
          const objList = {
            titls: timeData,
            median: formatPriceRoundUp(boxData[key]?.[2]),
            Q1: formatPriceRoundUp(boxData[key]?.[1]),
            Q3: formatPriceRoundUp(boxData[key]?.[3]),
            upperLimit: formatPriceRoundUp(boxData[key]?.[4]),
            lowerLimit: formatPriceRoundUp(boxData[key]?.[0]),
          };
          childrenArr.push(objList);
        } else {
          const objList = {
            titls: timeData,
            median: formatPriceRoundUp(dataSecond?.boxData[key]?.[2]),
            Q1: formatPriceRoundUp(dataSecond?.boxData[key]?.[1]),
            Q3: formatPriceRoundUp(dataSecond?.boxData[key]?.[3]),
            upperLimit: formatPriceRoundUp(dataSecond?.boxData[key]?.[4]),
            lowerLimit: formatPriceRoundUp(dataSecond?.boxData[key]?.[0]),
          };
          childrenArr.push(objList);
        }
      });
      obj.children = childrenArr;
      data.push(obj);
    });

  // column.forEach((item,index)=>{
  //   obj[item.dataIndex]=boxData[index]&&boxData[index][0]
  // })
  // data.push(obj);
  return data;
};

export const formatPriceRoundUp = (value, precision = 3) => {
  if (value === null || value === undefined) {
    return '-';
  }
  if (isNaN(value)) {
    return '-';
  }
  let num = Math.round(value * 10 ** precision) / 10 ** precision;
  let numData = num.toFixed(precision);

  return numData;
};
